package br.com.condominio.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import br.com.condominio.entity.Residencial;

@Repository("residencialDao")
public class ResidencialDAO {

	@PersistenceContext
	protected EntityManager entityManager;

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Residencial> findAll() {
		String jpql = "SELECT c from Residencial c order by c.resNome";
		Query query = entityManager.createQuery(jpql);
		List<Residencial> residencials = (List<Residencial>) query
				.getResultList();
		return residencials;
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Residencial> findByName(String nomeResidencial) {
		String jpql = " SELECT c from Residencial c where resNome like :resNome order by c.resNome";
		Query query = entityManager.createQuery(jpql);
		query.setParameter("resNome", nomeResidencial + "%");
		List<Residencial> residencials = (List<Residencial>) query
				.getResultList();
		return residencials;
	}

	@Transactional
	public Residencial create(Residencial residencial) {
		entityManager.persist(residencial);
		return residencial;
	}

	@Transactional
	public void update(Residencial residencial) {
		entityManager.merge(residencial);
	}

	@Transactional
	public void delete(Residencial residencial) {
		residencial = entityManager.find(Residencial.class,
				residencial.getResCodigo());
		entityManager.remove(residencial);
	}

	@Transactional
	public Residencial findById(Integer id) {
		String jpql = " SELECT c from Residencial c where c.resCodigo  = :id";
		Query query = entityManager.createQuery(jpql);
		query.setParameter("id", id );
		Residencial residencial = (Residencial) query
				.getSingleResult();
		return residencial;
	}
	
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}


}
